## Controller Python Script "anonymous_addscript"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind state=state
##bind subpath=traverse_subpath
##parameters=RESPONSE=None,type_name=None
##title=Create a thread or a post, for anonymous
##

from AccessControl import Unauthorized

try:
    # That's for Plone2.5
    from Products.CMFPlone import MessageFactory
    mf = MessageFactory('PloneGossip')
    MF = True
except:
    # That's for earlier Plone
    MF = False

have_permission = context.portal_membership.checkPermission
if type_name == 'PGPost' and not have_permission('PloneGossip: Add post', context):
    raise Unauthorized

if type_name == 'PGThread' and not have_permission('PloneGossip: Add thread', context):
    raise Unauthorized

if type_name not in ('PGThread', 'PGPost'):
    raise Unauthorized

request    = context.REQUEST
plone_tool = context.plone_utils

anon = context.portal_membership.isAnonymousUser()
if anon:
    member = 'Anonymous user'
else:
    member = context.portal_membership.getAuthenticatedMember().getId()

data = dict(
    text     = request.get('body_text',   None),
    title    = request.get('item_title',  None),
    author   = request.get('author_name', None),
    creators = [member,],
    )

# Is this threadable ?
if type_name == 'PGThread':
    data['isThreaded'] = request.get('isthreaded', False)


# Handles id generation
oid = plone_tool.normalizeString(request.get('item_title',  None))
if getattr(context, oid, None):
    oid = context.generateUniqueId(type_name)
new_id = context.invokeFactory(id=oid,
                               type_name=type_name,
                               **data)

o = getattr(context, new_id, None)
if o is None:
    raise Exception

tname = o.getTypeInfo().Title().lower()
response = context.REQUEST.get('RESPONSE', None)
if not MF:
    response.setHeader('Content-Type', 'text/html; charset=%s' % plone_tool.getSiteEncoding() or 'UTF-8')
    portal_status_message = context.translate(msgid=tname + '_submitted',
                                              default=tname + ' has been submitted',
                                              domain='PloneGossip')	

    return state.set(status='success', portal_status_message=portal_status_message)

elif MF:
    msg = mf(tname + '_submitted',
             tname + ' has been submitted')
    context.plone_utils.addPortalMessage(msg)
    return state.set()

return state.set(status='success')
